package com.lipert.sk2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Scanner;

public class ServerReceiver extends Thread {

	public static PrintWriter out = null;
	public static BufferedReader in = null;
	public static Socket serverSocket = null;
	public static Sender a = null;
	public static ArrayList<String> nickList = new ArrayList<String>();
	public static ArrayList<String> addressList = new ArrayList<String>();

	// Scanner in2 = null;

	public void run() {

		try {
			serverSocket = new Socket(InetAddress.getByName(GUI.ipText
					.getText()), Integer.parseInt((GUI.portText.getText())));
			in = new BufferedReader(new InputStreamReader(
					serverSocket.getInputStream()));
			out = new PrintWriter(
					ServerReceiver.serverSocket.getOutputStream(), true);
			System.out.println("tworze socket");

			a = new Sender();
			a.sendToServer(GUI.nickText.getText());

		} catch (UnknownHostException e1) {
			System.out.println("socket nie działa");
			e1.printStackTrace();
		} catch (IOException e1) {
			System.out.println("socket nie działa222");
			e1.printStackTrace();
		}

		while (true) {
			try {
				String temp = (in.readLine()).trim();
				if (!(temp.equals(null))) {
					if (!(temp.equals(""))) {
						// System.out.println("echo: " + temp);
						String tempData[] = temp.split(",");
						System.out.println("Nick: " + tempData[0] + " Adres: "
								+ tempData[1]);
						if (tempData[0].equals("EXIT")) {
							GUI.listModel.remove(addressList.indexOf(tempData[1]));
							GUI.listModel2.remove(addressList.indexOf(tempData[1]));
							nickList.remove(addressList.indexOf(tempData[1]));
							addressList
									.remove(addressList.indexOf(tempData[1]));
						} else {
							if (!nickList.contains(tempData[0])) {
								nickList.add(tempData[0]);
								for (int i = 0; i < ServerReceiver.nickList
										.size(); i++) {
									System.out.println(ServerReceiver.nickList
											.get(i));
									if (!GUI.listModel
											.contains(ServerReceiver.nickList
													.get(i)))
										GUI.listModel
												.addElement(ServerReceiver.nickList
														.get(i));
									if (!GUI.listModel2
											.contains(ServerReceiver.nickList
													.get(i)))
										GUI.listModel2
												.addElement(ServerReceiver.nickList
														.get(i));
								}
							}
							if (!addressList.contains(tempData[1])) {
								addressList.add(tempData[1]);
							}
						}

					}
				}
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
